package com.training.api.controller;

import com.training.base.ResponseUtils;
import com.training.bean.Course;
import com.training.jwt.JWTUtils;
import com.training.api.service.CollectService;
import com.training.utils.UrlUtils;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/api/collect")
public class CollectController {
    
    @Autowired
    private CollectService collectService;
    
    @Autowired
    private Gson gson;
    
    @Autowired
    private ResponseUtils responseUtils;
    
    /**
     * 收藏切换接口（收藏/取消收藏）
     * @param cid 课程内容ID
     * @param request HTTP请求对象
     * @return 操作结果
     */
    @PostMapping("/collect")
    public ResponseEntity<com.training.base.Result<Object>> collect(@RequestParam int cid, HttpServletRequest request) {
        try {
            // 从JWT token中获取用户ID
            int uid = JWTUtils.getUserIdFromRequest(request);
            // 判断当前是否已收藏
            boolean isCollected = collectService.isCollected(uid, cid);
            if (isCollected) {
                // 已收藏则取消收藏
                collectService.removeCollect(uid, cid);
                return responseUtils.success(null, "取消收藏成功");
            } else {
                // 未收藏则添加收藏
                collectService.addCollect(uid, cid);
                return responseUtils.success(null, "收藏成功");
            }
        } catch (Exception e) {
            return responseUtils.fail("操作失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户收藏列表
     * @param request HTTP请求对象
     * @return 收藏列表
     */
    @GetMapping("/getUserCollects")
    public ResponseEntity<com.training.base.Result<List<Course>>> getUserCollects(HttpServletRequest request) {
        try {
            // 从JWT token中获取用户ID
            int uid = JWTUtils.getUserIdFromRequest(request);
            List<Course> courses = collectService.getUserCollectCourses(uid);
            // 为每个课程动态构建完整封面URL，并添加收藏状态
            List<Course> coursesWithFullCoverUrls = courses.stream()
                    .peek(course -> {
                        if (course.getCover() != null && !course.getCover().isEmpty()) {
                            course.setCover(UrlUtils.buildFullUrl(request, course.getCover()));
                        }
                    })
                    .toList();
            return responseUtils.success(coursesWithFullCoverUrls, "获取收藏列表成功");
        } catch (Exception e) {
            return responseUtils.failWithType(500,"获取收藏列表失败：" + e.getMessage());
        }
    }
}